package org.dizena.base.web;

import org.apache.commons.lang3.StringUtils;
import org.dizena.base.avo.resp.Result;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class HttpErrorController implements ErrorController
{

    @Resource
    private ErrorAttributes errorAttributes;

    @RequestMapping("error")
    @ExceptionHandler(value = {Exception.class})
    public Result<String> error(HttpServletRequest request, HttpServletResponse response, final Exception ex, final WebRequest req)
    {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map<String, Object> attr = this.errorAttributes.getErrorAttributes(req, false);
        int status = response.getStatus();
        String message = String.valueOf(attr.getOrDefault("message", "error"));
        String error = String.valueOf(attr.getOrDefault("error", "error"));
        if (StringUtils.isNoneEmpty(error))
        {
            message = error + " and " + message;
        }
        return Result.error(status, message);
    }

    @Override
    public String getErrorPath()
    {
        return "/error";
    }

}